﻿using CatUtils.Utils.IoUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HostsTool.Currency.IoUtils
{
    internal class FileHelper
    {
        /// <summary>
        /// 文件是否存在，是否需要创建
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="CreateFlag"></param>
        /// <returns></returns>
        public static bool FileExits(String FilePath, bool CreateFlag = false)
        {
            if (File.Exists(FilePath))
            {
                return true;
            }
            else
            {
                if (CreateFlag)
                {
                    try
                    {
                        new FloderHelper().FloderExits(Path.GetDirectoryName(FilePath), true);

                        File.AppendAllText(FilePath, "", Encoding.UTF8);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        PrintLog.Log(ex);
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 用utf8读取文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReadAllTextUtf8(string path)
        {
            FileExits(path, true);
            string ReadText = "";
            try
            {
                using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open), System.Text.Encoding.UTF8))
                {
                    ReadText = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return ReadText;
        }

        /// <summary>
        /// 统一写入utf8的方法
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Content"></param>
        public static void AppendUTF8Text(String FilePath, String Content)
        {
            try { File.AppendAllText(FilePath, "\r\n" + Content, Encoding.UTF8); } catch (Exception ex) { PrintLog.Log(ex); }
        }

        /// <summary>
        /// 统一写入utf8的方法
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Content"></param>
        public static void AppendUTF8List(String FilePath, List<String> Content)
        {
            try
            {
                File.AppendAllText(FilePath, "\r\n", Encoding.UTF8);
                File.AppendAllLines(FilePath, Content, Encoding.UTF8);
            }
            catch (Exception ex) { PrintLog.Log(ex); }
        }

        /// <summary>
        /// 覆盖源文件，写入text
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Content"></param>
        public static void WriteUTF8Text(String FilePath, string Content)
        {
            try
            {
                new FloderHelper().FloderExits(new FloderNameHelper().GetFloderPath(FilePath), true);
                File.WriteAllText(FilePath, Content, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 覆盖源文件，写入list
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Content"></param>
        public static void WriteUTF8List(String FilePath, List<String> Content)
        {
            try
            {
                File.WriteAllLines(FilePath, Content, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 读取所有行 不存在则创建
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="CreateFlag"></param>
        /// <returns></returns>
        public static List<string> ReadAllLine(String FilePath, bool CreateFlag = true)
        {
            List<String> ReadAllLine = new List<string>();
            try
            {
                if (FileExits(FilePath))
                    ReadAllLine = File.ReadAllLines(FilePath).ToList<string>();
                else
                {
                    if (CreateFlag)
                        File.AppendAllText(FilePath, "", Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return ReadAllLine;
        }

        /// <summary>
        /// 选择文件  记住上次的路径
        /// </summary>
        /// <param name="InitialDirectory"></param>
        /// <param name="Filter"></param>
        /// <returns></returns>
        public string SelectFile(string InitialDirectory = "", string Filter = "所有文件(*.*)|*.*")
        {
            List<string> MultiFile = SelectMultiFile(InitialDirectory, Filter);
            return new ListHelper().GetFirst(MultiFile);
        }

        /// <summary>
        /// 选择多个文件  记住上次的路径
        /// </summary>
        /// <param name="InitialDirectory"></param>
        /// <param name="Filter"></param>
        /// <returns></returns>
        public List<string> SelectMultiFile(string InitialDirectory = "", string Filter = "所有文件(*.*)|*.*")
        {
            List<string> FileList = new List<string>();
            using (OpenFileDialog dialog = InitFileDialog(InitialDirectory, Filter))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    FileList = dialog.FileNames.ToList();
                }
            }
            return FileList;
        }

        /// <summary>
        /// 初始化文件选择框
        /// </summary>
        /// <param name="InitialDirectory"></param>
        /// <param name="Filter"></param>
        /// <returns></returns>
        private OpenFileDialog InitFileDialog(string InitialDirectory, string Filter)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            if (InitialDirectory != "")
                dialog.InitialDirectory = InitialDirectory;
            if (Filter != "")
                dialog.Filter = Filter;
            return dialog;
        }

        /// <summary>
        /// 文件重命名
        /// </summary>
        /// <param name="FilePath"></param>
        public void FileReName(string FilePath, string NewFilePath)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(FilePath);
                fileInfo.MoveTo(NewFilePath);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 判断文件大小是否超过了界限，超过返回false
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="FileSize">文件大小 KB</param>
        /// <returns></returns>
        public bool JudgementOfSize(String FileName, int FileSize)
        {
            FileInfo fi = new FileInfo(FileName);
            if (fi.Length > 1024 * FileSize)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 修改文件md5
        /// </summary>
        /// <param name="Filename"></param>
        public void ModifyMD5(String Filename)
        {
            if (!File.Exists(Filename))
            {
                Console.WriteLine("文件不存在");
                return;
            }
            else
            {
                //转化byte[]到list
                List<byte> ByteList = File.ReadAllBytes(Filename).ToList<byte>();
                ///添加一个二进制随机数
                ByteList.AddRange(Encoding.Default.GetBytes(Convert.ToString(new Random().Next(), 2)).ToList<byte>());
                try
                {
                    File.WriteAllBytes(Filename, ByteList.ToArray());
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                };
            }
        }

        /// <summary>
        /// 获取文件大小 返回的是byte
        /// </summary>
        /// <param name="sFullName"></param>
        /// <returns></returns>
        public long GetFileSizeForByte(string sFullName)
        {
            long lSize = 0;

            if (File.Exists(sFullName))
                lSize = new FileInfo(sFullName).Length;
            return lSize;
        }

        /// <summary>
        /// 获取文件大小 返回的是KB
        /// </summary>
        /// <param name="sFullName"></param>
        /// <returns></returns>
        public double GetFileSizeForKB(string sFullName)
        {
            long FactSize = GetFileSizeForByte(sFullName);
            Console.WriteLine(FactSize);
            return (FactSize / 1024.00);
        }

        /// <summary>
        /// 去重复行和空行，然后重新覆盖这个文件
        /// </summary>
        public void ToRepartLine(String FilePath)
        {
            List<String> AllLine = FileHelper.ReadAllLine(FilePath);

            File.Copy(FilePath, FilePath + ".bak", true);
            foreach (String line in File.ReadAllLines(FilePath))
            {
                if (line != "" && (!AllLine.Contains(line)))
                {
                    AllLine.Add(line.Trim());
                    Console.WriteLine("已读取" + line);
                }
            }
            File.WriteAllLines(FilePath, AllLine);
        }

        /// <summary>
        ///  移动文件  需要指示是否覆盖，若是不想覆盖，请调用FileNameHelper的createRandomFileName 创建不重复文件名
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="NewFilePath"></param>
        /// <param name="CoverFlag"></param>
        public void FileMove(String FilePath, String NewFilePath, bool CoverFlag = true)
        {
            try
            {
                new FloderHelper().FloderExits(Path.GetDirectoryName(NewFilePath), true);
                if (CoverFlag && File.Exists(NewFilePath))
                    FileDelete(NewFilePath);
                File.Move(FilePath, NewFilePath);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 复制文件  需要指示是否覆盖，若是不想覆盖，请调用FileNameHelper的createRandomFileName 创建不重复文件名
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="NewFilePath"></param>
        /// <param name="CoverFlag">是否覆盖</param>
        public void FileCopy(String FilePath, String NewFilePath, bool CoverFlag)
        {
            try
            {
                new FloderHelper().FloderExits(Path.GetDirectoryName(NewFilePath), true);
                if (CoverFlag && File.Exists(NewFilePath))
                    FileDelete(NewFilePath);
                File.Copy(FilePath, NewFilePath);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 删除文件的方法，会告诉你删除是否成功
        /// </summary>
        /// <param name="Filename"></param>
        /// <returns></returns>
        public bool FileDelete(String Filename)
        {
            try
            {
                File.Delete(Filename);
                return true;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                return false;
            }
        }
    }
}